using Identity.Application.Contracts.Common;
using Identity.Application.Contracts.Services;
using Identity.Application.Users.Commands;
using MediatR;

namespace Identity.Application.Users.CommandHandler;

public class ResetPasswordCommandHandler : IRequestHandler<ResetPasswordCommand, Result>
{
    private readonly IUserService _userService;
    private readonly IRedisService _redisService;

    public ResetPasswordCommandHandler(IUserService userService, IRedisService redisService)
    {
        _userService = userService;
        _redisService = redisService;
    }
    public async Task<Result> Handle(ResetPasswordCommand request, CancellationToken cancellationToken)
    {
        var user = await _userService.GetUserByEmailAsync(request.email);
        if (user == null) return Result.Failure("邮箱未注册");

        var resetToken = await _redisService.GetStringAsync($"reset_code:{request.code}");
        if (resetToken == null) return Result.Failure("验证码无效或过期");

        var result = await _userService.ResetPasswordAsync(user.Id, resetToken, request.newPassword);
        if (!result.Succeeded)
        {
            return Result.Failure(result.Error ?? "重设密码失败");
        }

        // 删除 Redis key，防止重复使用
        await _redisService.DeleteKeyAsync($"reset_code:{request.code}");
        return Result.Success();
    }
}
